Node.js - tutorial - HTTP server

revision:


build an HTTP server

To create an HTTP server, we include the http module (i.e. const http = require('http')).

The server is set to listen on the specified port, 3000 (i.e. const port = process.env.PORT || 3000). When the server is ready, the listen callback function is called.

The callback function we pass is the one that's going to be executed upon every request that comes in. Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).

request provides the request details. Through it, we access the request headers and request data.

response is used to populate the data we're going to return to the client.


making HTTP requests with Node.js

perform a GET request.

example

JS
        const https = require('https')
        const options = {
        hostname: 'example.com',
        port: 443,
        path: '/todos',
        method: 'GET'
        }

        const req = https.request(options, res => {
        console.log(`statusCode: ${res.statusCode}`)

        res.on('data', d => {
            process.stdout.write(d)
        })
        })

        req.on('error', error => {
        console.error(error)
        })

        req.end()
    

perform a POST request.

example

JS
        const https = require('https')
        
        const data = new TextEncoder().encode(
          JSON.stringify({
            todo: 'Buy the milk 🍼'
          })
        )
        
        const options = {
          hostname: 'whatever.com',
          port: 443,
          path: '/todos',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
          }
        }
        
        const req = https.request(options, res => {
          console.log(`statusCode: ${res.statusCode}`)
        
          res.on('data', d => {
            process.stdout.write(d)
          })
        })
        
        req.on('error', error => {
          console.error(error)
        })
        
        req.write(data)
        req.end()
    

PUT and DELETE requests use the same POST request format - you just need to change the options.method value to the appropriate method.


make an HTTP POST request using Node.js

There are many ways to perform an HTTP POST request in Node.js, depending on the abstraction level you want to use.

The simplest way to perform an HTTP request using Node.js is to use the Axios library.

example

JS
        const axios = require('axios')
        
        axios
          .post('https://whatever.com/todos', {
            todo: 'Buy the milk'
          })
          .then(res => {
            console.log(`statusCode: ${res.status}`)
            console.log(res)
          })
          .catch(error => {
            console.error(error)
          })
    

Axios requires the use of a 3rd party library.

A POST request is possible just using the Node.js standard modules, although it's more verbose than the preceding option.

example

JS
        const https = require('https')

        const data = JSON.stringify({
          todo: 'Buy the milk'
        })
        
        const options = {
          hostname: 'whatever.com',
          port: 443,
          path: '/todos',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
          }
        }
        
        const req = https.request(options, res => {
          console.log(`statusCode: ${res.statusCode}`)
        
          res.on('data', d => {
            process.stdout.write(d)
          })
        })
        
        req.on('error', error => {
          console.error(error)
        })
        
        req.write(data)
        req.end()
    

get HTTP request body data using Node.js

how to extract the data that was sent as JSON in the request body?

If you are using Express, that's quite simple: use the body-parser Node.js module.For example, to get the body of this request:

example

JS:
        const axios = require('axios')
        axios.post('https://whatever.com/todos', {
        todo: 'Buy the milk'
        })
    

This is the matching server-side code:

JS:
      const express = require('express')
      const app = express()

      app.use(
        express.urlencoded({
          extended: true
        })
      )

      app.use(express.json())

      app.post('/todos', (req, res) => {
        console.log(req.body.todo)
      })
    

If you're not using Express and you want to do this in vanilla Node.js, you need to do a bit more work, of course, as Express abstracts a lot of this for you.

The key thing to understand is that when you initialize the HTTP server using http.createServer(), the callback is called when the server got all the HTTP headers, but not the request body. The request object passed in the connection callback is a stream. So, we must listen for the body content to be processed, and it's processed in chunks.

We first get the data by listening to the stream data events, and when the data ends, the stream end event is called, once. So to access the data, assuming we expect to receive a string, we must concatenate the chunks into a string when listening to the stream data, and when the stream end, we parse the string to JSON.

example

Starting from Node.js v10 a for await .. of syntax is available for use that simplifies the code and makes it look more linear.